<template>
  <wd-popup v-model="show" position="bottom" >
    <view class="header">
       <view class="header-close">
         <wd-icon name="close" size="28rpx" color="#86909C" @click="show=false"></wd-icon>
       </view>
       <view class="header-title">上传文件</view>
    </view>
    <view class="choose-list">
      <image class="choose-item" mode="aspectFit"  @click="chooseImages" src="http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/miniapp/select-img.png" ></image>
      <image class="choose-item" mode="aspectFit"  @click="chooseVideo" src="http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/miniapp/select-video.png" ></image>
      <image class="choose-item" mode="aspectFit"  @click="chooseFile" src="http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/miniapp/select-file.png" ></image>
    </view>
  </wd-popup>
</template>
<script setup>
import {fileFormat,generateId} from "@/utils/utils"
import  {getFormDataParams,signatureUrl,getCurrentTime,getRandom,getSuffix} from "@/utils/file"
import { showLoading, hideLoading } from "../../../../utils/utils";
import {aliOssPermission} from "@/api/file"
const fileList = defineModel('fileList')
const show = defineModel('showUpload')

//上传图片
const chooseImages =  ()=> {
  uni.chooseImage({
    count: 100, //默认是9张
    extension:['png','jpg'],
    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'], //从相册选择
    success:async res =>  {
      let imgFile = res.tempFilePaths;
      imgFile.forEach(item => {
        if(!fileFormat(["jpg",'png'],item)){
          uni.showToast({title:'请上传jpg或png格式的图片',icon:'none'})
          return
        }
         uploadFn('image',item)
      })

    }
  })
}
//上传视频
const chooseVideo = (index)=> {
  uni.chooseVideo({
    count: 100,
    success: res => {
      console.log(res.size)
      let videoFile = res.tempFilePath;
      if(!fileFormat(["mp4"],videoFile)){
        uni.showToast({title:'请上传规定mp4格式的文件',icon:'none'})
        return
      }
      if(res.size>200*1024*1024){
        uni.showToast({title:'视频不能超过200M',icon:'none'})
        return
      }
     uploadFn('video',videoFile)
    },
    fail:(error)=>{
      uni.showToast({title:'请上传mp4格式的文件',icon:'none'})
    }
  })
}
//选择文件
const chooseFile = ()=>{
  uni.chooseMessageFile({
    type:"file",
    success: function (res) {
      console.log('uploadfile',res)
      let files = res.tempFiles;
      let uploadFlag = true
      files.map(item=>{
        if(!fileFormat(["docx","doc","rar","zip","xls","xlsx"],item.path)){
          uni.showToast({title:'请上传规定格式文件',icon:'none'})
          uploadFlag = false
        }
        if(item.size>200*1024*1024){
          uni.showToast({title:'文件不能超过200M',icon:'none'})
          uploadFlag = false
        }
      })
      if(uploadFlag){
        files.map(item=>{
          uploadFn('file',item)
        })

        // let filesPathArr = files.map(item=>{
        //   return item.path
        // })
        // filesPathArr.forEach(item=>{
        //   uploadFn('file',item)
        // })
      }

    }
  });
}
const uploadFn = async (type,item)=>{
  const host = 'https://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com';
  const uploadParam = await getFormDataParams()
  const filePath = type==='file'?item.path:item // 待上传文件的文件路径。
  const key = `MINIPROGRAM/${getCurrentTime()}-${getRandom()}.${getSuffix(filePath)}`
  const fileType = getSuffix(filePath)
  const fileName= type==='file'?item.name:getCurrentTime()+'.'+ fileType
  uni.uploadFile({
    url: host,
    filePath: filePath,
    name: 'file',
    formData: {
      key:key,
      ...uploadParam
    },
    success:async (res) => {
      if (res.statusCode === 204) {
        try {
          await aliOssPermission({objectName:key,cannedAccessControlList:'PublicRead'})
          showLoading("文件上传中...")
          const fileUrl = await signatureUrl(key);
          const resObj = {
            content: "",
            fileUrl: fileUrl ? `${fileUrl}`.split("?")[0] : "",
            fileId: generateId(),
            fileName,
            fileType
          };
          resObj.url = resObj.fileUrl;
          console.log("resobj",resObj)
          fileList.value.push(resObj)
          console.log("filelist",fileList.value)
          hideLoading()
        }catch (err){}
        hideLoading()
        // show.value = false
      }
    },
    fail: err => {
      console.log(err);
    }
  });
}


</script>
<style lang="scss" scoped>
@import "../../../../style/common.scss";
.header{
  text-align: center;
  position: relative;
  height: 96rpx;
  line-height: 96rpx;
  .header-close{
    position: absolute;
    left: 34rpx;
    top: 0rpx;
  }
  .header-title{
    @include fontStyle(32rpx,#000);
  }
}
.choose-list{
  @include flexStyle(space-around,center);
  padding: 40rpx 0rpx 60rpx 0rpx;
  .choose-item{
    @include blockStyle(160rpx,160rpx,none);
    object-fit: contain;
  }
}
</style>